<!-- eslint-disable no-undef -->
<script setup>
import { ref } from 'vue'
import { userResetPwdService } from '@/api/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'

const password = ref({
    old_pwd: '',
    new_pwd: '',
    re_pwd: ''
})

const checkDifferent = (rule, value, callback) => {
  // 校验新密码和原密码不能一样
  if (value === password.value.old_pwd) {
    callback(new Error('新密码不能与原密码一样'))
  } else {
    callback()
  }
}
const checkSameAsNewPwd = (rule, value, callback) => {
  // 校验确认密码必须和新密码一样
  if (value !== password.value.new_pwd) {
    callback(new Error('确认密码必须和新密码一样'))
  } else {
    callback()
  }
}
const rules = ref({
  old_pwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 15, message: '原密码长度在6-15位之间', trigger: 'blur' }
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '新密码长度在6-15位之间', trigger: 'blur' },
    { validator: checkDifferent, trigger: 'blur' }
  ],
  re_pwd: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '确认密码长度在6-15位之间', trigger: 'blur' },
    { validator: checkSameAsNewPwd, trigger: 'blur' }
  ]
})

const userSotre = useUserStore()
const router = useRouter()
const pwdRef = ref()
const onUpdate = async () => {
    await pwdRef.value.validate()
    await userResetPwdService(password.value)
    ElMessage.success('更新密码成功')
    // 密码修改成功后需要清楚user数据
    userSotre.setToken('')
    userSotre.setUser({})
    // 跳转到登录页
    router.push('/login')
}
const onReset = () => {
    pwdRef.value.resetFields()
}
</script>
<template>
    <page-container title="重置密码">
        <el-form ref="pwdRef" :rules="rules" :model="password">
            <el-form-item style="width: 50%" label="原密码" prop="old_pwd">
                <el-input v-model="password.old_pwd" type="password"></el-input>
            </el-form-item>
            <el-form-item style="width: 50%" label="新密码" prop="new_pwd">
                <el-input v-model="password.new_pwd" type="password"></el-input>
            </el-form-item>
            <el-form-item style="width: 50%" label="重复密码" prop="re_pwd">
                <el-input v-model="password.re_pwd" type="password"></el-input>
            </el-form-item>
            <el-button type="primary" size="large" @click="onUpdate">修改密码</el-button>
            <el-button size="large" @click="onReset">重置</el-button>
        </el-form>
    </page-container>
</template>